package cn.elwy.rcp.ui.util;

import org.eclipse.jface.resource.FontDescriptor;
import org.eclipse.jface.resource.FontRegistry;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.widgets.Display;

/**
 * 获取字体工具类
 * @author huangsq
 * @version 2.0, 2015-02-19
 * @since 1.0, 2015-02-19
 */
public class FontUtil {

  private static final FontRegistry fontRegistry = JFaceResources.getFontRegistry();

  // 将构造方法设置为private,禁止创建该类的实例
  private FontUtil() {
  }

  /**
   * 根据RGB获取颜色对象
   * @param symbolicName 字体标识,格式"Courier New|10|NORMAL"
   * @return
   */
  public static Font getFont(String symbolicName) {
    Font font = fontRegistry.get(symbolicName);
    if (font == null || font.isDisposed()) {
      FontDescriptor fontDescriptor = fontRegistry.getDescriptor(symbolicName);
      if (fontDescriptor != null) {
        font = fontDescriptor.createFont(Display.getCurrent());
        fontRegistry.put(symbolicName, font.getFontData());
      } else {
        try {
          String fontKey[] = symbolicName.split("|");
          if (fontKey != null && fontKey.length == 3) {
            int height = Integer.parseInt(fontKey[1]);
            int style = SWTUtil.toSWTConstant(fontKey[2], "NORMAL");
            FontData fontData = new FontData(fontKey[0], height, style);
            fontRegistry.put(symbolicName, new FontData[] { fontData });
            font = fontRegistry.get(symbolicName);
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    return font;
  }

}
